/*
The MIT License (MIT)

Copyright (c) 2013 Mike Dapiran, Brian May, Richard Pospesel, and Bert Wierenga

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "hhdFactory.h"
#include "hhdIHObject.h"
#include "hhdIContent.h"
#include "hhdStringBuilder.h"

#if HHD_PLATFORM_WINDOWS
#include <crtdbg.h>
#endif //HHD_PLATFORM_WINDOWS

namespace hhd
{
#ifdef NEW_DELETE_FACTORY
    Vector<IHObject*>* Factory::_register_buffer = NULL;
    Logger Factory::_logger("logs/factory.log");

    void Factory::initialize()
    {
        for(size_t k = 0; k < _register_buffer->size(); k++)
        {
            StringBuilder sb;
            sb << "Factory registering: " << (*_register_buffer)[k]->hObjectName() << ": #" << (*_register_buffer)[k]->hObjectIdInstance();
			String string;
			sb >> string;
            _logger.write(string);
        }
    }

    IHObject* Factory::acquire(IHObject* in_object)
    {
        return in_object->instance();
    }

    void Factory::release(IHObject* in_object)
    {
        if(in_object == (void*)0xdddddddd  || in_object == (void*)0xfeeefeee || in_object == (void*)0xcdcdcdcd)
        {
            error("Found a bad pointer!");
        }

        in_object->reset();
        delete in_object;

    }
    void Factory::safeRelease(IHObject** in_object)
    {
        delete *in_object;
        *in_object = NULL;
    }

    void Factory::finalize()
    {
        for(size_t k = 0; k < _register_buffer->size(); k++)
        {
            IHObject* o =  _register_buffer->get(k);
            o->reset();
            delete o;
        }

        delete _register_buffer;
    }
#endif

#ifdef NEW_DELETE_RECORD_FACTORY
    unsigned int Factory::m_classes = 0;
    unsigned int* Factory::m_preallocated_in_use = NULL;
    unsigned int* Factory::m_max_preallocated_in_use = NULL;
    unsigned int* Factory::m_total_preallocated_ever_used = NULL;

    DataStructures::DynamicList<CoreEngine::IPreallocated*>* Factory::m_prototypes = NULL;
    hhd::Utils::Logger* Factory::m_logger = NULL;

    // initialize the arrays where we store stats
    void Factory::initialize()
    {
        m_preallocated_in_use = new unsigned int[m_classes];
        m_max_preallocated_in_use = new unsigned int[m_classes];
        m_total_preallocated_ever_used = new unsigned int[m_classes];

        for(int k = 0; k < m_classes; k++)
        {
            m_preallocated_in_use[k]= m_max_preallocated_in_use[k] = m_total_preallocated_ever_used[k] = 0;
        }

    }

    // based on a prototype, get a new one
    IPreallocated* Factory::acquire(IPreallocated* in_object)
    {
        // get the id type
        int t_id = in_object->myPreAllocatedID();
        // update stats
        m_total_preallocated_ever_used[t_id]++;
        m_preallocated_in_use[t_id]++;
        if(m_preallocated_in_use[t_id] > m_max_preallocated_in_use[t_id])
        {
            m_max_preallocated_in_use[t_id] = m_preallocated_in_use[t_id];
        }

        return in_object->instance();
    }

    // return to the factory
    void Factory::release(IPreallocated* in_object)
    {
        int t_id = in_object->myPreAllocatedID();
        in_object->finalize();

        m_preallocated_in_use[t_id]--;
        delete in_object;
    }

    // return to the factoyr and set pointer to NULL
    void Factory::safeRelease(IPreallocated** in_object)
    {
        int t_id = (*in_object)->myPreAllocatedID();
        (*in_object)->finalize();

        m_preallocated_in_use[t_id]--;
        delete *in_object;
        *in_object = NULL;
    }

    // write allocation report to the log
    void Factory::finalize()
    {
        // write us an XML file dood
        fstream xml;
        xml.open("factory_allocation.xml", fstream::out);
        if(xml.is_open() == true)
        {
            xml << "<FactoryAllocation>" << endl;

            for(int k = 0; k < m_classes; k++)
            {
                xml << "\t<Allocate type=\"" << m_prototypes->get(k)->preAllocatedName() << "\" count=\"" <<  m_max_preallocated_in_use[k] * 2 << "\" />" << endl;
            }

            xml << "</FactoryAllocation>" << endl;
            xml.close();
        }
        else
        {
            cout << "Could not write factory allocation XML" << endl;
        }


        for(int k = 0; k < m_classes; k++)
        {
            hhd::DataStructures::HStringStream hss;
            hss << "Allocation Report for \"" <<  m_prototypes->get(k)->preAllocatedName() << "\"  Max concurrently in use: " << m_max_preallocated_in_use[k] << ";  Total ever used: " << m_total_preallocated_ever_used[k];
            m_logger->writeLog(hhd::Utils::Logger::Manager, hss.toString());
        }
    }
#endif

#ifdef PREALLOCATE_FACTORY
    unsigned int Factory::m_classes = 0;

    DataStructures::DynamicList<CoreEngine::IPreallocated*>* Factory::m_prototypes = NULL;
    hhd::Utils::Logger* Factory::m_logger = NULL;
    Factory::ObjectPool** Factory::m_object_pools = NULL;

    void Factory::initialize()
    {
        // Load in the factory allocation file
        ifstream is;
        is.open("factory_allocation.xml");

        stringstream ss;
        if(is.is_open())
        {
            string line;
            while(! is.eof())
            {
                getline(is, line);
                ss << line;
            }
        }
        else
        {
            hhd::DataStructures::HStringStream ehss;
            ehss << "Trouble opening factory_allocation.xml";
            throw hhd::Utils::Exception::buildException(__LINE__, __FILE__, ehss.toString());
        }

        // parse the xml

        TiXmlDocument document;
        document.Parse(ss.str().c_str());

        hhd::DataStructures::DynamicList<const char*> class_names;
        hhd::DataStructures::DynamicList<int> class_counts;


        TiXmlElement* node = document.RootElement();
        if(node)
        {
            TiXmlNode* child = 0;
            while(child = node->IterateChildren(child))
            {
                TiXmlElement* child_element = child->ToElement();
                if(!child_element)
                {
                    continue;
                }

                const char* name = child_element->Attribute("type");
                int count;
                child_element->QueryIntAttribute("count", &count);

//					cout << name << ": " << count << endl;

                class_names.addLast(name);
                class_counts.addLast(count);
            }
        }


        m_object_pools = new Factory::ObjectPool*[m_classes];

        for(unsigned int k = 0; k < m_classes; k++)
        {
            m_object_pools[k] = NULL;
            const char* name = m_prototypes->get(k)->preAllocatedName();
            for(int i = 0; i < class_names.size(); i++)
            {
                if(strcmp(name, class_names[i]) == 0)
                {
                    m_object_pools[k] = new ObjectPool();
                    m_object_pools[k]->initialize(m_prototypes->get(k), class_counts[i]);
                    break;
                }
            }
            if(m_object_pools[k] == NULL)
            {
//					cout << name << " not found in factory_allocation.xml; allocating 128" << endl;
                m_object_pools[k] = new ObjectPool();
                m_object_pools[k]->initialize(m_prototypes->get(k), 128);
            }


        }
        // load xml file and allocate these guys
    }

    IPreallocated* Factory::acquire(IPreallocated* in_object)
    {
        int t_id = in_object->myPreAllocatedID();

        IPreallocated* result = m_object_pools[t_id]->pop();
        if(result == NULL)
        {
            result =in_object->instance();
        }

        return result;
    }

    void Factory::release(IPreallocated* in_object)
    {
        int t_id = in_object->myPreAllocatedID();

        in_object->finalize();
        m_object_pools[t_id]->push(in_object);
    }

    void Factory::safeRelease(IPreallocated** in_object)
    {
        int t_id = (*in_object)->myPreAllocatedID();

        (*in_object)->finalize();
        m_object_pools[t_id]->push(*in_object);

        *in_object = NULL;
    }

    void Factory::finalize()
    {
    }

    // methods for ObjectPool
    #pragma region OBJECT_POOL_METHODS
    Factory::ObjectPool::ObjectPool()
    {
        IPreallocated** first_row = new IPreallocated*[ROW_WIDTH];
        data.addLast(first_row);
        capacity = ROW_WIDTH;
        pool_size = 0;
    }

    Factory::ObjectPool::~ObjectPool()
    {
        for(int k = 0 ; k < data.size(); k++)
        {
            delete[] data[k];
        }
    }

    void  Factory::ObjectPool::initialize(IPreallocated* in_prototype, unsigned int in_count)
    {
        for(unsigned int k = 0; k < in_count; k++)
        {
            this->push(in_prototype->instance());
        }
    }

    void Factory::ObjectPool::push(IPreallocated* in_object)
    {
        if(pool_size == capacity)
        {
            IPreallocated** next_row = new IPreallocated*[ROW_WIDTH];
            data.addLast(next_row);
            capacity += ROW_WIDTH;
        }

        int row = pool_size / ROW_WIDTH;
        int column = pool_size % ROW_WIDTH;

        data[row][column] = in_object;
        pool_size++;
    }

    IPreallocated* Factory::ObjectPool::pop()
    {
        if(pool_size == 0)
        {
            return NULL;
        }
        pool_size--;
        int row = pool_size / ROW_WIDTH;
        int column = pool_size % ROW_WIDTH;

        IPreallocated* result = data[row][column];

        return result;
    }

    int Factory::ObjectPool::size()
    {
        return pool_size;
    }
    #pragma endregion
#endif

}
